﻿using System.Reflection;

namespace DimensionsHelper.Client.Navigation;

public class NavigationTargetData
{
    private static readonly Assembly Assembly = typeof(NavigationTargetData).Assembly;

    private const string ClineNamespace = "DimensionsHelper.Client";
    
    private Type? _cachedModelType;
    private Type? _cachedPageType;
    private string? _fullScope;
    
    internal NavigationTargetData? ParentData { get; set; }

    public string IconGlyph { get; set; } = string.Empty;

    public string Description { get; set; } = string.Empty;

    public string PrimaryName { get; set; } = string.Empty;

    public string? Scope { get; set; }
    
    public string? Key { get; set; }
    
    public bool NoScope { get; set; }

    public List<NavigationTargetData> Items { get; set; } = [];

    
    private string? GetFullScope()
    {
        if (NoScope)
        {
            return null;
        }
        
        if (_fullScope != null)
        {
            return _fullScope;
        }

        if (ParentData != null)
        {
            _fullScope = ParentData.GetFullScope();
        }

        if (!string.IsNullOrEmpty(Scope))
        {
            if (!string.IsNullOrEmpty(_fullScope))
            {
                _fullScope = Scope + ".";
            }

            _fullScope += Scope;
        }
        
        return _fullScope;
    }
    
    
    public Type? PageType => _cachedPageType ??= Assembly.GetType(GetPageTypeName(GetFullScope(), PrimaryName));

    public Type? ModelType => _cachedModelType ??= Assembly.GetType(GetModelTypeName(GetFullScope(), PrimaryName));


    private static string GetPageTypeName(string? scope, string primaryName)
    {
        return $"{ClineNamespace}.Views{(string.IsNullOrEmpty(scope) ? "" : $".{scope}")}.{primaryName}Page";
    }

    private static string GetModelTypeName(string? scope, string primaryName)
    {
        return
            $"{ClineNamespace}.ViewModels{(string.IsNullOrEmpty(scope) ? "" : $".{scope}")}.{primaryName}ViewModel";
    }
}